<template>
  <Card>
    <div class="searchBox">
      <Form ref="searchForm" :label-width="90" :model="searchForm" class="search-formApply" inline>
        <Form-item label="单号：" prop="number">
          <Input
            v-model="searchForm.number"
            clearable
            placeholder="支持模糊搜索"
            style="width: 200px"
            type="text"
          />
        </Form-item>
        <Form-item label="车牌号：" prop="license_plate_num">
          <Input
            v-model="searchForm.license_plate_num"
            clearable
            placeholder="支持模糊搜索"
            style="width: 200px"
            type="text"
          />
        </Form-item>
        <Form-item label="节点：" prop="node_id">
          <Select v-model="searchForm.node_id" :disabled="disableNodeId" style="width: 200px">
            <Option :key="-1" :value="-1">全部</Option>
            <Option
              v-for="item in workflowNodeList"
              :key="item.id"
              :value="item.id"
            >{{ item.node_name }}
            </Option>
          </Select>
        </Form-item>
        <Form-item label="状态：" prop="status">
          <Select v-model="searchForm.status" style="width: 200px">
            <Option :key="-1" :value="-1">全部</Option>
            <Option v-for="(item,index) in dict" :key="index" :value="index">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item label="日期范围：" prop="date">
          <DatePicker
            v-model="searchForm.date"
            placeholder="请选择日期范围"
            placement="bottom-start"
            style="width: 200px"
            type="daterange"
          ></DatePicker>
        </Form-item>
        <Form-item style="margin-left:-90px;">
          <Button icon="md-search" type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
        </Form-item>
      </Form>
    </div>
    <div class="btns">
      <Button
        v-if="displayAddBtn"
        icon="ios-add"
        target="_self"
        type="primary"
        @click="toAdd"
      >添加
      </Button>
      <Button v-if="displayDelAllBtn" icon="md-trash" type="error" @click="delAll">删除</Button>
    </div>
    <div class="table">
      <Row v-if="displaySelected">
        <Alert show-icon>
          已选择
          <span class="select-count">{{ selectCount }}</span> 项
          <a class="select-clear" @click="clearSelectAll">清空</a>
        </Alert>
      </Row>
      <Row>
        <Table
          ref="table"
          :columns="columns"
          :data="data"
          :loading="loading"
          border
          size="small"
          @on-selection-change="showSelect"
        >
          <template slot="action" slot-scope="{ row }">
            <Button
              ghost
              style="color:#2d8cf0;font-size: 12px;"
              type="text"
              @click="preview(row)"
            >查看
            </Button>
            <Divider type="vertical"/>
            <Button
              :disabled="row.editBtnDisabled"
              :style="row.editBtnStyle"
              ghost
              type="text"
              @click="edit(row.id)"
            >编辑
            </Button>
            <Divider type="vertical"/>
            <Button
              :disabled="row.delBtnDisabled"
              :style="row.delBtnStyle"
              ghost
              type="text"
              @click="del(row)"
            >删除
            </Button>
          </template>
        </Table>
      </Row>
      <Row class="page" justify="end" type="flex">
        <Page
          :current="searchForm.pageNumber"
          :page-size="searchForm.pageSize"
          :total="total"
          show-total
          @on-change="changePage"
        />
      </Row>
    </div>
    <Modal
      v-model="modalApplyVisible"
      :mask-closable="false"
      :styles="{top: '20px'}"
      :title="modalApplyTitle"
      :width="900"
    >
      <Form
        ref="formApply"
        :label-width="110"
        :model="formApply"
        :rules="formApplyValidate"
        label-position="right"
      >
        <Alert v-if="openErrorAlert" show-icon type="error">
          审核意见
          <span slot="desc">{{ formApply.reason }}</span>
        </Alert>
        <Divider v-if="openErrorAlert"/>
        <Col span="12">
        <FormItem v-if="isShowNumber" label="单号：" prop="number">
          <Input v-model="formApply.number" readonly type="text"/>
        </FormItem>
        </Col>
        <div v-if="modalApplyType < 2">
          <Col span="12">
          <FormItem label="车辆线路：" prop="line">
            <Select v-model="formApply.line" clearable placeholder="选择线路">
              <Option v-for="item in lines" :key="item.value" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          </Col>
          <Col span="12">
          <FormItem label="车牌号：" prop="license_plate_num">
            <Select v-model="formApply.license_plate_num" placeholder="选择车牌号">
              <Option
                v-for="item in licensePlateNumList"
                :key="item.value"
                :value="item.value"
              >{{ item.label }}
              </Option>
            </Select>
          </FormItem>
          </Col>
        </div>
        <div v-else>
          <Col span="12">
          <FormItem label="车辆线路：" prop="line">
            <Input v-model="formApply.line" :readonly="isReadonly" type="text"/>
          </FormItem>
          </Col>
          <Col span="12">
          <FormItem label="车牌号：" prop="license_plate_num">
            <Input v-model="formApply.license_plate_num" :readonly="isReadonly" type="text"/>
          </FormItem>
          </Col>
        </div>
        <Col span="12">
        <FormItem label="日期：" prop="date">
          <DatePicker
            v-model="formApply.date"
            :clearable="false"
            :readonly="isReadonly"
            format="yyyy-MM-dd"
            placeholder="选择时间"
            type="date"
          ></DatePicker>
        </FormItem>
        </Col>
        <Col span="12">
        <FormItem label="驾驶员：" prop="driver">
          <Input v-model="formApply.driver" readonly type="text"/>
        </FormItem>
        </Col>
        <Col span="24">
        <FormItem label="维修情况：" prop="description">
          <Input
            v-model="formApply.description"
            :autosize="{minRows: 4,maxRows: 5}"
            :readonly="isReadonly"
            :rows="4"
            placeholder="请输入..."
            type="textarea"
          ></Input>
        </FormItem>
        </Col>
        <Col span="24">
        <FormItem label="上传照片：" prop="driverUploadFile">
          <upload-pic-thumb-multiple
            ref="driverUploadFile"
            :params="{saveDir: 'mrApply', type: 'pic'}"
            :readonly="isReadonly"
            @on-change="formApply.driverUploadFile=$event"
          ></upload-pic-thumb-multiple>
          <div
            style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
          >1、支持jpg、jpeg、png格式的图片，最大不超过600KB
          </div>
          <div
            style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
          >2、请确保上传完毕之后再提交保存
          </div>
        </FormItem>
        </Col>
        <div v-if="displayHouqinForm">
          <Divider>后勤部</Divider>
          <FormItem label="维修费估值：" prop="appraisal">
            <InputNumber
              v-model="formApply.appraisal"
              :max="10000000"
              :min="0"
              :readonly="isHouQinReadonly"
              style="width: 100%"
            ></InputNumber>
          </FormItem>
          <FormItem label="上传照片：" prop="houqinUploadFile">
            <upload-pic-thumb-multiple
              ref="houqinUploadFile"
              :params="{saveDir: 'mrApply', type: 'pic'}"
              :readonly="isHouQinReadonly"
              @on-change="formApply.houqinUploadFile=$event"
            ></upload-pic-thumb-multiple>
            <div
              style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
            >1、支持jpg、jpeg、png格式的图片，最大不超过600KB
            </div>
            <div
              style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
            >2、请确保上传完毕之后再提交保存
            </div>
          </FormItem>
        </div>
        <div v-if="displayWeixiuForm">
          <Divider>维修厂</Divider>
          <Button icon="ios-add" style="margin-bottom: 10px;" type="primary" @click="toAddWeixiu">添加</Button>
          <div style="margin-bottom:15px">
            <Table
              ref="selection"
              :columns="payColumns"
              :data="payData"
              :loading="payLoading"
              border
              height="350"
              size="small"
              stripe
            >
              <template slot="action" slot-scope="{ row }">
                <a
                  class="edit"
                  size="small"
                  style="color:#2d8cf0;font-size: 12px;"
                  type="text"
                  @click="editWeixiu(row)"
                >编辑</a>
                <Divider type="vertical"/>
                <a class="del" style="color:#ed4014;font-size: 12px;" @click="delWeixiu(row)">删除</a>
              </template>
            </Table>
          </div>
          <FormItem label="上传照片：" prop="weixiuUploadFile">
            <upload-pic-thumb-multiple
              ref="weixiuUploadFile"
              :params="{saveDir: 'mrApply', type: 'pic'}"
              :readonly="isHouQinReadonly"
              @on-change="formApply.weixiuUploadFile=$event"
            ></upload-pic-thumb-multiple>
            <div
              style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
            >1、支持jpg、jpeg、png格式的图片，最大不超过600KB
            </div>
            <div
              style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;"
            >2、请确保上传完毕之后再提交保存
            </div>
          </FormItem>
        </div>
      </Form>
      <div v-if="isShowAuditRecord">
        <Divider>审核记录</Divider>
        <div id="auditRecord">
          <div v-for="item of auditRecord" :key="item.id" class="stepCard">
            <div>
              <p>
                <Icon size="30" type="md-contact"/>
                {{ item.nodeName }}
              </p>
              <span>时间：{{ item.created_at }}&nbsp;&nbsp;&nbsp;&nbsp;操作：{{ item.resultName }}</span>
              <span v-if="item.reason !== null && item.reason !== ''">退回理由：{{ item.reason }}</span>
            </div>
            <div>
              <p>单据编号：{{ item.number }}</p>
            </div>
            <div></div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button v-if="isShowCancelBtn" type="text" @click="handleApplyCancel">取消</Button>
        <Button
          v-if="isShowSaveBtn"
          :loading="saveApplyLoading"
          type="info"
          @click="handleApplySubmit('save')"
        >保存
        </Button>
        <Button
          v-if="isShowSaveSubmitBtn"
          :loading="submitApplyLoading"
          type="primary"
          @click="handleApplySubmit('submit')"
        >保存并提交审核
        </Button>
        <Button
          v-if="isShowWeixiuSubmitBtn"
          :loading="submitWeixiuLoading"
          type="primary"
          @click="handleWeixiuSubmit"
        >保存并提交审核
        </Button>
        <Dropdown v-if="isShowAuditBtn" style="margin-left: 20px" trigger="click" @on-click="audit">
          <Button type="primary">
            审核
            <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="pass">审核通过</DropdownItem>
            <DropdownItem name="back" style="color: #ed4014">驳回</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
    </Modal>
    <Modal
      v-model="modal"
      :mask-closable="false"
      :styles="{top: '20px'}"
      title="添加维修内容"
      width="900"
      @on-cancel="cancel('add')"
    >
      <Form ref="addPayForm" :label-width="130" :model="addPayForm" :rules="addPayFormValidate">
        <FormItem label="维修内容：" style="width:99%;">
          <Input
            v-model="addPayForm.content"
            :autosize="{minRows: 4,maxRows: 5}"
            :rows="4"
            placeholder="请输入维修内容"
            type="textarea"
          />
        </FormItem>
        <Form-item label="维修类型：" style="width:49%;">
          <Input v-model="addPayForm.type" placeholder="请输入维修类型"/>
        </Form-item>
        <Form-item label="维修费用：" style="width:49%;">
          <Input v-model="addPayForm.amount" placeholder="请输入维修费用"/>
        </Form-item>
      </Form>
      <div slot="footer">
        <Button @click="handlePayReset('addPayForm')">重置</Button>
        <Button style="margin-left:8px" type="primary" @click="submitPay('addPayForm')">保存</Button>
      </div>
    </Modal>
    <Modal
      v-model="editModal"
      :mask-closable="false"
      :styles="{top: '20px'}"
      title="编辑维修内容"
      width="900"
      @on-cancel="cancel('edit')"
    >
      <Form ref="editPayForm" :label-width="130" :model="editPayForm" :rules="editPayFormValidate">
        <FormItem label="维修内容：" style="width:99%;">
          <Input
            v-model="editPayForm.content"
            :autosize="{minRows: 4,maxRows: 5}"
            :rows="4"
            placeholder="请输入维修内容"
            type="textarea"
          />
        </FormItem>
        <Form-item label="维修类型：" style="width:49%;">
          <Input v-model="editPayForm.type" placeholder="请输入维修类型"/>
        </Form-item>
        <Form-item label="维修费用：" style="width:49%;">
          <Input v-model="editPayForm.amount" placeholder="请输入维修费用"/>
        </Form-item>
      </Form>
      <div slot="footer">
        <Button @click="handlePayReset('editPayForm')">重置</Button>
        <Button style="margin-left:8px" type="primary" @click="submitPay('editPayForm')">保存</Button>
      </div>
    </Modal>
    <!--    审核原因模态窗口-->
    <Modal
      v-model="reasonModal"
      :mask-closable="false"
      title="请简要说明原因"
      @on-cancel="cancelReasonForm"
    >
      <Form ref="reasonForm" :model="reasonForm">
        <FormItem prop="reason">
          <Input
            v-model="reasonForm.reason"
            :rows="5"
            placeholder="请输入"
            size="large"
            type="textarea"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button :loading="reasonAuditLoading" type="primary" @click="reasonAudit()">确定</Button>
      </div>
    </Modal>
  </Card>
</template>
<script>
import moment from 'moment'
import {licensePlateNumList} from '../../api/bus'
import UploadPicThumbMultiple from '../my-components/upload-pic-thumb-multiple'
import {applyList, auditApply, destroyApply, editAppply, storeApply, storeWeixiu, updateApply} from '../../api/mrApply'
import {workflowData} from '../../api/material'
import {dictData} from '../../api/insure'

export default {
  components: {
    UploadPicThumbMultiple
  },
  data() {
    return {
      displayHouqinForm: false,
      displayWeixiuForm: false,
      isShowAuditRecord: false,
      nodeKey: '',
      reasonAuditLoading: false,
      reasonModal: false,
      openErrorAlert: false,
      reason: '',
      isShowCancelBtn: true,
      isShowSaveBtn: true,
      isShowSaveSubmitBtn: true,
      isShowWeixiuSubmitBtn: false,
      isDisabled: false,
      isReadonly: false,
      isHouQinReadonly: false,
      isShowNumber: false,
      isShowAuditBtn: false,
      total: 0,
      selectCount: 0,
      selectList: [],
      searchForm: {
        number: '',
        date: [null, null],
        license_plate_num: '',
        status: -1,
        node_id: -1,
        pageNumber: 1,
        pageSize: 10
      },
      reasonForm: {
        reason: ''
      },
      formApply: {
        nodeType: '',
        nodeKey: '',
        number: '',
        line: '',
        appraisal: 0,
        license_plate_num: '',
        driver: this.$store.getters.user.name, // 默认当前用户
        user_id: this.$store.getters.user.id, // 默认当前用户ID
        date: moment().format('YYYY-MM-DD'), //默认今天
        description: '',
        driverUploadFile: [],
        houqinUploadFile: [],
        weixiuUploadFile: []
      },
      formCost: {
        line: '',
        license_plate_num: '',
        driver: this.$store.getters.user.name, // 默认当前用户
        date: moment().format('YYYY-MM-DD'), //默认今天
        description: ''
      },
      loading: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          type: 'index',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '单号',
          key: 'number',
          width: 150,
          align: 'left'
        },
        {
          title: '车牌号',
          key: 'license_plate_num',
          width: 120,
          align: 'center'
        },
        {
          title: '单据日期',
          key: 'date',
          width: 150,
          align: 'center'
        },
        {
          title: '创建人',
          key: 'user_name',
          width: 120,
          align: 'left'
        },
        {
          title: '节点状态',
          key: 'status_role',
          width: 200,
          align: 'left'
        },
        {
          title: '维修情况',
          key: 'description',
          width: 200,
          align: 'left'
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 170,
          align: 'right'
        },
        {
          title: '操作',
          slot: 'action',
          width: 230,
          fixed: 'right',
          align: 'center'
        }
      ],
      data: [],
      costData: [],
      submitApplyLoading: false,
      submitWeixiuLoading: false,
      saveApplyLoading: false,
      submitCostLoading: false,
      modalApplyType: 0,
      modalCostType: 0,
      modalApplyVisible: false,
      modalCostVisible: false,
      formApplyValidate: {
        line: [
          {
            required: true,
            message: '车辆线路不能为空',
            trigger: 'change',
            type: 'number'
          }
        ],
        license_plate_num: [
          {
            required: true,
            message: '车牌号不能为空',
            trigger: 'change',
            type: 'string'
          }
        ],
        // date: [{required: true, message: "时间不能为空", trigger: "blur", type: 'date'}],
        // appraisal: [{ required: true, message: '金额不能为空', trigger: 'blur', type: 'number' }],
      },
      formCostValidate: {
        license_plate_num: [
          {required: true, message: '车牌号不能为空', trigger: 'blur'}
        ]
      },
      modalApplyTitle: '',
      modalCostTitle: '',
      licensePlateNumList: [],
      lines: [],
      displayAddBtn: true,
      displayDelAllBtn: true,
      disableNodeId: true,
      displaySelected: true,
      auditRecord: [],
      addPayForm: {
        content: '',
        type: null,
        amount: null
      },
      payColumns: [
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '维修内容',
          key: 'content',
          align: 'center'
        },
        {
          title: '维修类型',
          key: 'type',
          align: 'center'
        },
        {
          title: '维修金额',
          key: 'amount',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          width: 120,
          fixed: 'right',
          align: 'center'
        }
      ],
      editPayForm: {},
      modal: false,
      editModal: false,
      payData: [],
      payLoading: false,
      addPayFormValidate: {},
      editPayFormValidate: {},
      workflowNodeList: [],
      dict: [],
    }
  },
  watch: {},
  mounted() {
    setTimeout(() => {
      this.init()
    }, 2000)
  },
  created() {
    this.setButtonStatus()
    this.getWorkflow()
    this.getLicensePlateNumList()
    this.getDictData()
    this.getLinesArray()
  },
  methods: {
    async getLinesArray() {
      this.lines = await this.getLines()
    },
    cancel(form) {
      if (form === 'add') {
        this.handlePayReset('addPayForm')
      } else {
        this.handlePayReset('editPayForm')
      }
    },
    getWorkflow() {
      workflowData({title: '维修申请单'}).then(res => {
        if (res.data.result) {
          this.workflowNodeList = res.data.result
          const _this = this
          this.workflowNodeList.forEach(function (e, i) {
            if (e.node_key === _this.nodeKey) {
              _this.searchForm.node_id = e.id
            }
          })
        }
      })
    },
    getDictData() {
      dictData({title: '申请单状态'}).then(res => {
        if (res.data.result) {
          this.dict = res.data.result
        }
      })
    },
    handlePayReset(form) {
      this.addPayForm = this.editPayForm = {
        content: '',
        type: null,
        amount: null
      }
    },
    editWeixiu(e) {
      const row = e
      this.editPayForm.index = row._index
      this.editPayForm.content = row.content
      this.editPayForm.type = row.type
      this.editPayForm.amount = row.amount
      this.editModal = true
    },
    delWeixiu(row) {
      this.payData.splice(row._index, 1)
    },
    submitPay(form) {
      if (form === 'addPayForm') {
        const formData = this.addPayForm
        this.payData.push(formData)
        this.modal = false
        this.cancel('add')
      } else {
        const formData = this.editPayForm
        const index = formData.index
        delete formData.index
        this.payData.splice(index, 1, formData)
        this.editModal = false
        this.cancel('edit')
      }
    },
    audit(name) {
      this.$refs.formApply.validate(valid => {
        if (valid) {
          if (name === 'pass') {
            const params = {
              id: this.formApply.id,
              nodeType: name,
              reason: '',
              nodeKey: this.nodeKey
            }
            if (this.nodeKey === 'wr_apply_logistics') {
              params.appraisal = parseInt(this.formApply.appraisal)
              params.houqinUploadFile = this.formApply.houqinUploadFile
            }
            if (this.nodeKey === 'wr_cost_finance') {
              params.nodeType = 'end'
            }
            this.toAuditApply(params)
          } else {
            this.reasonModal = true
            this.reasonForm.id = this.formApply.id
            this.reasonForm.nodeType = name
            this.reasonForm.nodeKey = this.nodeKey
            this.reasonForm.reason = ''
          }
        }
      })
    },
    cancelReasonForm() {
      this.$refs.reasonForm.resetFields()
    },
    changePage(v) {
      this.searchForm.pageNumber = v
      this.getMrApplyList()
      this.clearSelectAll()
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false)
    },
    del(row) {
      this.$Modal.confirm({
        title: '确认删除',
        loading: true,
        content: '您确认要删除此条数据吗？',
        onOk: () => {
          const ids = row.id
          // 批量删除
          destroyApply(ids).then(res => {
            this.$Modal.remove()
            if (res.data === true) {
              this.$Message.success(res.message)
              this.getMrApplyList()
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未选择要删除的数据')
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        loading: true,
        content: '您确认要删除所选的 ' + this.selectCount + ' 条数据？',
        onOk: () => {
          let ids = ''
          this.selectList.forEach(function (e) {
            ids += e.id + ','
          })
          ids = ids.substring(0, ids.length - 1)
          // 批量删除
          destroyApply(ids).then(res => {
            this.$Modal.remove()
            if (res.data === true) {
              this.$Message.success(res.message)
              this.getMrApplyList()
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    },
    edit(id) {
      this.displayHouqinForm =
        this.nodeKey === 'wr_apply_logistics' ||
        this.nodeKey === 'wr_apply_leader'
      this.isShowAuditRecord = true
      this.isShowCancelBtn = true
      this.isShowSaveBtn = true
      this.isShowSaveSubmitBtn = true
      this.isShowAuditBtn = false
      this.modalApplyType = 1
      this.modalApplyTitle = '编辑'
      editAppply(id).then(res => {
        this.isShowNumber = true
        this.formApply = res.data
        this.formApply.driver = res.data.user_name
        this.formApply.appraisal =
          this.formApply.appraisal !== null
            ? parseInt(this.formApply.appraisal)
            : 0
        this.openErrorAlert =
          this.formApply.reason != null && this.formApply.reason !== ''
        this.auditRecord = res.data.auditRecord
        // 先清空上传列表，再显示已上传图片
        this.$refs.driverUploadFile.handleClearFiles()
        this.$refs.driverUploadFile.setData(res.data.apply_file.driver)
        if (this.displayHouqinForm) {
          this.$refs.houqinUploadFile.handleClearFiles()
          this.$refs.houqinUploadFile.setData(res.data.apply_file.houqin)
        }
        this.isReadonly = false
        this.modalApplyVisible = true
      })
    },
    getLicensePlateNumList() {
      licensePlateNumList().then(res => {
        const data = []
        res.data.forEach(function (e, i) {
          data.push({
            label: e,
            value: e
          })
        })
        this.licensePlateNumList = data
      })
    },
    getMrApplyList() {
      this.loading = true
      this.clearSelectAll()
      applyList(this.searchForm).then(res => {
        this.loading = false
        if (res.data) {
          this.data = res.data.mrApplyRecord
          this.total = res.data.count
        }
      })
    },
    handleApplyCancel() {
      this.modalApplyVisible = false
      this.$refs.formApply.resetFields()
    },
    handleApplySubmit(e) {
      this.$refs.formApply.validate(valid => {
        if (valid) {
          this.submitApplyLoading = e === 'submit'
          this.saveApplyLoading = e === 'save'
          this.formApply.nodeType = e
          this.formApply.nodeKey = this.nodeKey
          if (
            this.nodeKey === 'wr_apply_driver' ||
            this.nodeKey === 'wr_apply_driver_leader'
          ) {
            this.formApply.appraisal = 0
            this.formApply.houqinUploadFile = []
          }
          if (this.nodeKey === 'wr_apply_repairer') {
            this.formApply.weixiu = this.payData
          } else {
            this.formApply.weixiuUploadFile = []
          }
          if (this.modalApplyType === 0) {
            delete this.formApply.id
            storeApply(this.formApply).then(res => {
              this.submitApplyLoading = this.saveApplyLoading = false
              if (res.data) {
                this.$Message.success(res.message)
                this.getMrApplyList()
                this.modalApplyVisible = false
              } else {
                this.$Message.error(res.message)
              }
            })
          } else if (this.modalApplyType === 1) {
            updateApply(this.formApply, this.formApply.id).then(res => {
              this.submitApplyLoading = this.saveApplyLoading = false
              if (res.data) {
                this.$Message.success('更新成功')
                this.getMrApplyList()
                this.modalApplyVisible = false
              } else {
                this.$Message.error(res.message)
              }
            })
          } else {
          }
        }
      })
    },
    handleWeixiuSubmit() {
      this.$refs.formApply.validate(valid => {
        if (valid) {
          this.submitWeixiuLoading = true
          const params = {
            detail: this.payData,
            weixiuUploadFile: this.formApply.weixiuUploadFile,
            nodeKey: this.nodeKey,
            nodeType: 'submit'
          }
          storeWeixiu(params, this.formApply.id).then(res => {
            this.submitWeixiuLoading = false
            if (res.data) {
              this.$Message.success('修改成功')
              this.getMrApplyList()
              this.modalApplyVisible = false
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getMrApplyList()
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getMrApplyList()
    },
    init() {
      this.isShowAuditBtn = true
      this.getMrApplyList()
    },
    preview(row) {
      this.displayHouqinForm =
        this.nodeKey !== 'wr_apply_driver' &&
        this.nodeKey !== 'wr_apply_driver_leader' &&
        this.nodeKey !== 'wr_apply_repairer'
      this.displayWeixiuForm =
        this.nodeKey === 'wr_apply_repairer' ||
        this.nodeKey === 'wr_cost_logisitics' ||
        this.nodeKey === 'wr_cost_finance'
      this.isShowAuditRecord = this.nodeKey !== 'wr_apply_repairer'
      this.isShowWeixiuSubmitBtn = this.nodeKey === 'wr_apply_repairer'
      this.isShowCancelBtn = false
      this.isShowSaveBtn = false
      this.isShowSaveSubmitBtn = false
      this.isShowAuditBtn =
        row.status === 2 && this.nodeKey === row.process.node.node_key && row.process.node.node_key !== 'wr_apply_repairer'
      this.modalApplyType = this.nodeKey === 'wr_apply_repairer' ? 0 : 2
      this.modalApplyTitle = '查看'
      editAppply(row.id).then(res => {
        this.isShowNumber = true
        this.formApply = res.data
        this.payData = res.data.detail
        this.formApply.driver = res.data.user_name
        this.formApply.appraisal =
          this.formApply.appraisal !== null ? parseInt(this.formApply.appraisal) : 0
        this.openErrorAlert =
          this.formApply.reason != null && this.formApply.reason !== ''
        this.auditRecord = res.data.auditRecord
        // 先清空上传列表，再显示已上传图片
        this.$refs.driverUploadFile.handleClearFiles()
        this.$refs.driverUploadFile.setData(res.data.apply_file.driver)
        if (this.displayHouqinForm) {
          this.$refs.houqinUploadFile.handleClearFiles()
          this.$refs.houqinUploadFile.setData(res.data.apply_file.houqin)
        }
        if (this.displayWeixiuForm) {
          this.$refs.weixiuUploadFile.handleClearFiles()
          this.$refs.weixiuUploadFile.setData(res.data.apply_file.weixiu)
        }
        // 字段只读
        this.isHouQinReadonly = false
        this.isReadonly = true
        this.isDisabled = true
        this.modalApplyVisible = true
      })
    },
    reasonAudit() {
      this.reasonAuditLoading = true
      this.toAuditApply(this.reasonForm)
    },
    setButtonStatus() {
      const roleName = this.$store.getters.user.roleName[0]
      // 非司机用户，隐藏按钮和功能
      if (roleName !== '维修-司机' && roleName !== '超级管理员') {
        this.displayAddBtn = false
        this.displayDelAllBtn = false
        this.displaySelected = false
      }
      this.nodeKey =
        roleName === '维修-司机'
          ? 'wr_apply_driver'
          : roleName === '维修-车队长'
            ? 'wr_apply_driver_leader'
            : roleName === '维修-后勤部'
              ? 'wr_apply_logistics'
              : roleName === '维修-分管领导'
                ? 'wr_apply_leader'
                : roleName === '维修-维修厂'
                  ? 'wr_apply_repairer'
                  : roleName === '维修-维修后勤部'
                    ? 'wr_cost_logisitics'
                    : roleName === '维修-财务部'
                      ? 'wr_cost_finance'
                      : 'admin'
    },
    showSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    toAddWeixiu() {
      this.modal = true
    },
    toAdd() {
      this.isShowAuditRecord = false
      this.isShowCancelBtn = true
      this.isShowSaveBtn = true
      this.isShowSaveSubmitBtn = true
      this.isShowAuditBtn = false
      this.isShowNumber = false
      this.modalApplyType = 0
      this.modalApplyTitle = '添加'
      this.$refs.formApply.resetFields()
      this.$refs.driverUploadFile.handleClearFiles()
      this.submitApplyLoading = this.saveAndSubmitApplyLoading = false
      this.isShowWeixiuSubmitBtn = false
      delete this.formApply.id
      this.isReadonly = false
      this.modalApplyVisible = true
    },
    toAuditApply(params) {
      auditApply(params).then(res => {
        if (res.data.result === true) {
          if (res.data.nodeType === 'pass' || res.data.nodeType === 'end') {
            this.$Message.success(res.message)
          } else {
            this.reasonAuditLoading = false
            this.reasonModal = false
            this.$Message.error(res.message)
          }
          this.modalApplyVisible = false
          this.getMrApplyList()
        }
      })
    }
  }
}
</script>
<style scoped>
/*去除竖行分割线margin*/
.ivu-table-row .ivu-divider-vertical {
  margin: 0;
}

/* 审核记录 */
#auditRecord {
  padding: 0 2%;
}

#auditRecord .title {
  font-family: "Font Awesome 5 Pro Solid", "Font Awesome 5 Pro Regular",
  "Font Awesome 5 Pro", serif;
  font-weight: 900;
  font-style: normal;
  font-size: 16px;
  margin-top: 15px;
}

#auditRecord .stepCard {
  border: 1px solid rgba(215, 232, 244, 1);
  background-color: #f7fbfe;
  height: 120px;
  width: 90%;
  padding: 0 1%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  position: relative;
  left: 35px;
}

#auditRecord .stepCard > div:first-child {
  font-family: "微软雅黑", serif;
  font-weight: 400;
  font-size: 14px;
  color: #666;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

#auditRecord .stepCard > div:first-child > span {
  margin-top: 10px;
  color: #999;
}

#auditRecord .stepCard > div:nth-child(2) {
  margin-top: 20px;
  color: #666;
}

#auditRecord .stepCard > div:nth-child(2) > div {
  height: 70px;
  width: 120px;
  display: flex;
  white-space: nowrap;
  justify-content: space-between;
  line-height: 100px;
}

#auditRecord .stepCard > div:nth-child(2) > div img {
  width: 100%;
  height: 100%;
}

#auditRecord .stepCard > div:last-child {
  position: absolute;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: 1px solid #9ed1f5;
  left: -30px;
  top: 52px;
}

#auditRecord .pointIndex {
  background-color: #9ed1f5;
}
</style>
